import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"
import axios from "axios"

interface ProductDetailState {
  loading: boolean,
  error: string | null,
  data: any
}

const initialState: ProductDetailState = {
  loading: true,
  error: null,
  data: null
}

export const getProductDetail = createAsyncThunk(
  'productDetail/getProductDetail',
  async (touristRouteId: string, thunkAPI) => {
    const { data } = await axios.get(`http://82.157.43.234:8080/api/touristRoutes/${touristRouteId}`, {
      headers: {
        'x-icode': 'EDE45279EB142953'
      }
    })
    return data

  }
)


export const productDetailSlice = createSlice({
  name: 'productDetail',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getProductDetail.pending, (state) => {
        state.loading = true
      })
      .addCase(getProductDetail.fulfilled, (state, action) => {
        state.data = action.payload
        state.loading = false
        state.error = null
      })
      .addCase(getProductDetail.rejected, (state, action) => {
        state.loading = false
        if (typeof action.payload === 'string') {
          state.error = action.payload
        } else {
          state.error = null
        }

      })
  }
})